跳到主要内容

278 第一个错误的版本

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnto1s/

https://leetcode.cn/problems/first-bad-version/description/

cost: 6m52s

// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

class Solution {
public:
int firstBadVersion(int n) {
if (isBadVersion(1)) {
return 1;
}
int left = 1, right = n;
while (left < right) {
if (left == right - 1) {
return right;
}
int mid = left + (right - left) / 2;
bool bad = isBadVersion(mid);
if (bad) {
right = mid;
} else {
left = mid;
}
}
return -1;
}
};
  • 时间复杂度:O(log(n))
  • 空间复杂度:O(1)